#include <hd_led.h>
#include <hd_oled.h>
#include <hd_oled_protocol_i2c.h>
#include <delay.h>
#include <pd_dma.h>
#include <pd_i2c_hd.h>
#include "main.h"


#define ARRAY_SIZE(x)       sizeof(x) / sizeof(x[0])
#define USE_HARDWARE_SPI    1
#define USE_HARDWARE_I2C    1

OLED oled;
uint8_t dataA[] = {0x01, 0x02, 0x03, 0x04};
uint8_t dataB[4] = {4, 3, 2, 1};


extern void SystemClock_Config(void);

void oled_instance(OLED *oled);


int main(void) {
    SystemClock_Config();

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    oled_instance(&oled);

    OLED_printf(&oled, 0, 0, " DMA M2M");

    // 转运前源数据
    OLED_printf(&oled, 00, 16, "%02d", dataA[0]);
    OLED_printf(&oled, 24, 16, "%02d", dataA[1]);
    OLED_printf(&oled, 48, 16, "%02d", dataA[2]);
    OLED_printf(&oled, 72, 16, "%02d", dataA[3]);

    // 转运前目标数据
    OLED_printf(&oled, 00, 32, "%2d", dataB[0]);
    OLED_printf(&oled, 24, 32, "%2d", dataB[1]);
    OLED_printf(&oled, 48, 32, "%2d", dataB[2]);
    OLED_printf(&oled, 72, 32, "%2d", dataB[3]);
    OLED_refresh(&oled);

    DMA dma;
    DMA_constructor(&dma, DMA2, dataA, dataB,
                    4, LL_DMA_CHANNEL_1, LL_DMA_STREAM_2);
    DMA_init(&dma);

    delay_ms(1000);

    // 转运后目标数据
    OLED_printf(&oled, 00, 48, "%02d", dataB[0]);
    OLED_printf(&oled, 24, 48, "%02d", dataB[1]);
    OLED_printf(&oled, 48, 48, "%02d", dataB[2]);
    OLED_printf(&oled, 72, 48, "%02d", dataB[3]);
    OLED_refresh(&oled);

    while (1) {
    }
}


void oled_instance(OLED *oled) {
    // I2C gpio init
    static GPIO oledSckGPIO, oledSdaGPIO;
    GPIO_constructor(&oledSckGPIO, GPIOB, LL_GPIO_PIN_10); // I2Cx_SCK
    GPIO_constructor(&oledSdaGPIO, GPIOB, LL_GPIO_PIN_11); // I2Cx_SDA

#ifdef USE_HARDWARE_I2C
    static I2CHardware i2c2;
    I2CHardware_constructor(&i2c2, I2C2, &oledSckGPIO, &oledSdaGPIO);
#elif USE_SIMULATE_I2C
    static I2CSimulate i2c2;
    I2CSimulate_constructor(&i2c2, &oledSckGPIO, &oledSdaGPIO);
#endif
    I2C_init((I2C *)&i2c2);

    // OLED protocol of I2C
    static OLEDProtocolI2C oledProtocolI2c;
    OLEDProtocolI2C_constructor(&oledProtocolI2c, (I2C *)&i2c2);

    // OLED font instance.
    static OLEDFont oledFont;
    OLEDFont_contructor(&oledFont, NULL);

    // OLED instance of 4-PIN(I2C)
    OLED_constructor(oled, (OLEDProtocol *)&oledProtocolI2c, &oledFont);

    OLED_init(oled);

    OLED_clear(oled);
    OLED_refresh(oled);
}
